package com.ruoyi.sycs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.base.domain.SyType;
import com.ruoyi.base.domain.bo.SyTypeBo;
import com.ruoyi.base.domain.vo.SyTypeJudgeVo;
import com.ruoyi.base.domain.vo.SyTypeVo;
import com.ruoyi.base.mapper.SyTypeMapper;
import com.ruoyi.base.service.ISyTypeService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.TreeBuildUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.sycs.domain.bo.BsJudgeBaseBo;
import com.ruoyi.sycs.domain.vo.BsJudgeBaseVo;
import com.ruoyi.sycs.domain.BsJudgeBase;
import com.ruoyi.sycs.mapper.BsJudgeBaseMapper;
import com.ruoyi.sycs.service.IBsJudgeBaseService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 判定依据主Service业务层处理
 *
 * @author zyb
 * @date 2024-04-08
 */
@RequiredArgsConstructor
@Service
public class BsJudgeBaseServiceImpl implements IBsJudgeBaseService {

    private final BsJudgeBaseMapper baseMapper;

    private final SyTypeMapper syTypeMapper;

    /**
     * 查询判定依据主
     */
    @Override
    public BsJudgeBaseVo queryById(Long judgeId) {
        return baseMapper.selectVoById(judgeId);
    }

    /**
     * 查询判定依据主列表
     */
    @Override
    public TableDataInfo<BsJudgeBaseVo> queryPageList(BsJudgeBaseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BsJudgeBase> lqw = buildQueryWrapper(bo);
        Page<BsJudgeBaseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询判定依据主列表
     */
    @Override
    public List<BsJudgeBaseVo> queryList(BsJudgeBaseBo bo) {
        LambdaQueryWrapper<BsJudgeBase> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BsJudgeBase> buildQueryWrapper(BsJudgeBaseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BsJudgeBase> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getJudgeName()), BsJudgeBase::getJudgeName, bo.getJudgeName());
        lqw.eq(StringUtils.isNotBlank(bo.getSyType()), BsJudgeBase::getSyType, bo.getSyType());
        lqw.eq(StringUtils.isNotBlank(bo.getSyType2()), BsJudgeBase::getSyType2, bo.getSyType2());
        lqw.eq(StringUtils.isNotBlank(bo.getSyType3()), BsJudgeBase::getSyType3, bo.getSyType3());
        return lqw;
    }

    /**
     * 新增判定依据主
     */
    @Override
    public Boolean insertByBo(BsJudgeBaseBo bo) {
        BsJudgeBase add = BeanUtil.toBean(bo, BsJudgeBase.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setJudgeId(add.getJudgeId());
        }
        return flag;
    }

    /**
     * 修改判定依据主
     */
    @Override
    public Boolean updateByBo(BsJudgeBaseBo bo) {
        BsJudgeBase update = BeanUtil.toBean(bo, BsJudgeBase.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BsJudgeBase entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除判定依据主
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据试验类别查询明细
     *
     * @param syType
     * @return
     */
    @Override
    public List<BsJudgeBase> getListBySyType(Long syType) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("del_flag", "0");
        wrapper.eq("sy_type", syType);
        wrapper.orderByAsc("sort");
//        wrapper.orderByDesc("create_time");
        return baseMapper.selectList(wrapper);
    }

    /**
     * 根据试验类别获取明细分页
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public Page<BsJudgeBase> pageBySyType(BsJudgeBaseBo bo, PageQuery pageQuery) {
        if (ObjectUtils.isEmpty(bo.getSyType())) {
            return new Page<>();
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("del_flag", "0");
        wrapper.eq("sy_type", bo.getSyType());
        wrapper.orderByAsc("sort");
//        wrapper.orderByAsc("create_time");
        Page page = baseMapper.selectPage(pageQuery.build(), wrapper);
        return page;
    }

    /**
     * 获取技术指标 树列表
     *
     * @param type
     * @return
     */
    @Override
    public List<Tree<Long>> bsJudgeBaseTree(SyType type) {
        LambdaQueryWrapper<SyType> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SyType::getDelFlag, "0")
            .eq(ObjectUtil.isNotNull(type.getSyTypeId()), SyType::getSyTypeId, type.getSyTypeId())
            .eq(ObjectUtil.isNotNull(type.getParentId()), SyType::getParentId, type.getParentId())
            .like(StringUtils.isNotBlank(type.getSyTypeName()), SyType::getSyTypeName, type.getSyTypeName())
            .le(ObjUtil.isNotNull(type.getLevel()), SyType::getLevel, type.getLevel()) // <= level
            .orderByAsc(ObjectUtils.isNotEmpty(type.getCreateTime()), SyType::getCreateTime);
        List<SyType> types = syTypeMapper.selectList(lqw);
        // 如果是最末节点,则设置type为end
        for (int i = 0; i < types.size(); i++) {
            SyType syType = types.get(i);
            List<SyType> child = syTypeMapper.getChild(syType.getSyTypeId());
            if (ObjectUtils.isEmpty(child)) {
                types.get(i).setType("end");
            } else {
                types.get(i).setType(null);
            }
        }
        // 查询判定依据并添加作为子节点展示
        for (int i = 0; i < types.size(); i++) {
            SyType syType = types.get(i);
            Long syTypeId = syType.getSyTypeId();
            List<BsJudgeBase> list = this.getListBySyType(syTypeId);
            for (BsJudgeBase detail : list) {
                SyType entity = new SyType();
                entity.setDelFlag(detail.getDelFlag());
                entity.setCreateBy(detail.getCreateBy());
                entity.setCreateTime(detail.getCreateTime());
                entity.setUpdateBy(detail.getUpdateBy());
                entity.setUpdateTime(detail.getUpdateTime());
                entity.setParentId(syTypeId);
                entity.setSyTypeName(detail.getJudgeName());
                entity.setSyTypeId(detail.getJudgeId());
                entity.setType("detail-" + detail.getJudgeId()); // 标识该条为明细数据
                types.add(entity);
            }
        }
        return buildTypeTreeSelect(types);
    }

    /**
     * 获取技术指标 树列表 根据试验类型
     *
     * @param type
     * @return
     */
    @Override
    public List<Tree<Long>> bsJudgeBaseTreeBySyType(SyTypeBo type) {
        LambdaQueryWrapper<SyType> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SyType::getDelFlag, "0")
//            .eq(ObjectUtil.isNotNull(type.getSyTypeId()), SyType::getSyTypeId, type.getSyTypeId())
            .eq(ObjectUtil.isNotNull(type.getSyTypeId()), SyType::getParentId, type.getSyTypeId())
            .like(StringUtils.isNotBlank(type.getSyTypeName()), SyType::getSyTypeName, type.getSyTypeName())
            .le(ObjUtil.isNotNull(type.getLevel()), SyType::getLevel, 3) // <= level
            .orderByAsc(ObjectUtils.isNotEmpty(type.getCreateTime()), SyType::getCreateTime);
        List<SyType> types = syTypeMapper.selectList(lqw);
        if (ObjectUtils.isNotEmpty(types)) {
            // 查询判定依据并添加作为子节点展示
            for (int i = 0; i < types.size(); i++) {
                SyType syType = types.get(i);
                Long syTypeId = syType.getSyTypeId();
                List<BsJudgeBase> list = this.getListBySyType(syTypeId);
                for (BsJudgeBase detail : list) {
                    SyType entity = new SyType();
                    entity.setDelFlag(detail.getDelFlag());
                    entity.setCreateBy(detail.getCreateBy());
                    entity.setCreateTime(detail.getCreateTime());
                    entity.setUpdateBy(detail.getUpdateBy());
                    entity.setUpdateTime(detail.getUpdateTime());
                    entity.setParentId(syTypeId);
                    entity.setSyTypeName(detail.getJudgeName());
                    entity.setSyTypeId(detail.getJudgeId());
                    entity.setType("detail-" + detail.getJudgeId()); // 标识该条为明细数据
                    types.add(entity);
                }
            }
        }
        return buildTypeTreeSelect(types);
    }

    /**
     * 根据试验id获取报告列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<SyTypeVo> page(SyTypeBo bo, PageQuery pageQuery) {
        if (ObjectUtils.isEmpty(bo.getParentId())) {
            return TableDataInfo.build(new Page<>());
        }
        // 查询子集
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("del_flag", "0");
        wrapper.eq("parent_id", bo.getParentId());
        wrapper.orderByAsc("create_time");
        Page page = syTypeMapper.selectPage(pageQuery.build(), wrapper);
        // 没有子集查询明细
        if (ObjectUtils.isNotEmpty(page) && CollectionUtils.isEmpty(page.getRecords())) {
            BsJudgeBaseBo judgeBaseBo = new BsJudgeBaseBo();
            judgeBaseBo.setSyType(bo.getParentId().toString());
            Page<BsJudgeBase> basePage = pageBySyType(judgeBaseBo, pageQuery);
            Page subPage = new Page();
            List subRecords = new ArrayList();
            if (ObjectUtils.isNotEmpty(basePage.getRecords())) {
                List<BsJudgeBase> records = basePage.getRecords();
                for (BsJudgeBase record : records) {
                    SyTypeJudgeVo entity = new SyTypeJudgeVo();
                    entity.setParentId(bo.getParentId());
                    entity.setSyTypeId(Long.valueOf(record.getSyType()));
                    entity.setSyTypeName(record.getJudgeName());
                    entity.setJudgeName(record.getJudgeName());
                    entity.setJudgeId(record.getJudgeId());
                    entity.setSort(record.getSort());
                    entity.setType("detail"); // 标识明细对应数据
                    subRecords.add(entity);
                }
                subPage.setRecords(subRecords);
            }
            return TableDataInfo.build(subPage);
        } else {
            return TableDataInfo.build(page);
        }
    }

    public List<Tree<Long>> buildTypeTreeSelect(List<SyType> types) {
        if (CollUtil.isEmpty(types)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(types, (type, tree) ->
            tree.setId(type.getSyTypeId())
                .setParentId(type.getParentId())
                .setName(type.getSyTypeName())
                .setWeight(type.getType()));
    }

//    @Deprecated
//    public Long getRandomUUID() {
//        return Long.valueOf((int) (Math.random() * 1000000000));
//    }
}
